﻿#region Copyright RenGuiYou. All rights reserved.

//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================

#endregion

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Pandora;
using PandoraEditor;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Callbacks;
#if UNITY_IOS
using UnityEditor.iOS.Xcode;
#endif
using UnityEngine;
using UnityEngine.iOS;

namespace NeatlyEditor
{
    public static class NeatlyProjectPacker
    {
        private static readonly string[] SCENE_LEVELS = { "Assets/Scene/GameMain.unity" };

        public static void ExportProject()
        {
#if UNITY_ANDROID
            AndroidExportGradle();
#elif UNITY_IOS
        	IOSExport();
#endif
        }

        #region Windows

        //打包exe
        public static void WindowsExportEXE()
        {
            SetPlayerSetting();
            string pathExport = $"{NeatlyEditorConfig.PATH_WIN64}/{BuildSetting.ProjectBuildSetting.product_name}.exe";
            PdrFileUtil.DeleteDirectory(NeatlyEditorConfig.PATH_WIN64);
            PdrFileUtil.CreateDirectoryFromFile(pathExport);
            BuildPipeline.BuildPlayer(SCENE_LEVELS, pathExport, BuildTarget.StandaloneWindows64, BuildOptions.None);
            PdrFileUtil.DeleteDirectory($"{NeatlyEditorConfig.PATH_WIN64}/{BuildSetting.ProjectBuildSetting.product_name}_BackUpThisFolder_ButDontShipItWithYourGame");
            PdrFileUtil.DeleteDirectory($"{NeatlyEditorConfig.PATH_WIN64}/{BuildSetting.ProjectBuildSetting.product_name}_BurstDebugInformation_DoNotShip");
        }

        #endregion

        #region Android

        //导出gradle工程
        public static void AndroidExportGradle()
        {
            SetPlayerSetting();
            EditorUserBuildSettings.exportAsGoogleAndroidProject = true;
            PdrFileUtil.DeleteDirectory(NeatlyEditorConfig.PATH_ANDROID_TEMP_PROJECT);
            BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
            buildPlayerOptions.scenes = SCENE_LEVELS;
            buildPlayerOptions.locationPathName = NeatlyEditorConfig.PATH_ANDROID_TEMP_PROJECT;
            buildPlayerOptions.target = BuildTarget.Android;
            if (CommandParam.UseAab)
            {
                EditorUserBuildSettings.buildAppBundle = true;
                PlayerSettings.Android.useAPKExpansionFiles = true;
            }
            else
            {
                EditorUserBuildSettings.buildAppBundle = false;
                PlayerSettings.Android.useAPKExpansionFiles = false;
            }

            BuildPipeline.BuildPlayer(buildPlayerOptions);
            AndroidCopyFile(new[] { "Il2CppOutputProject", "jniLibs", "jniStaticLibs", "assets" });
            //处理abb资源
            var aabToResource = $"{NeatlyEditorConfig.PATH_ANDROID_PROJECT}/UnityDataAssetPack";
            PdrFileUtil.DeleteDirectory(aabToResource);
            if (CommandParam.UseAab)
            {
                var aabFromResource = $"{NeatlyEditorConfig.PATH_ANDROID_TEMP_PROJECT}/UnityDataAssetPack";
                PdrFileUtil.CopyDirectory(aabFromResource, aabToResource);
            }

            Debug.Log("Android Export Gradle complete.");
        }

        //打包apk
        public static void AndroidExportApk()
        {
            string assembleNxtCmd = CommandParam.Develop ? "Debug" : "Release";
            string assemblePreCmd = CommandParam.UseAab ? "bundle" : "assemble";
            string arguments = $"{assemblePreCmd}{assembleNxtCmd} --no-daemon";
            PdrFileUtil.DeleteDirectory(NeatlyEditorConfig.PATH_ANDROID_OUTPUTS);
            PdrCMDHelper.ProcessCommand(BuildSetting.LocalServerSetting.path_gradle, arguments, NeatlyEditorConfig.PATH_ANDROID_PROJECT);
            NeatlyLocalServerHelper.PackageAndroidToLocalServer();
        }

        private static void AndroidCopyFile(string[] folderArray)
        {
            if (!Directory.Exists(NeatlyEditorConfig.PATH_ANDROID_PROJECT))
            {
                Debug.Log("AndroidProject未创建!!!");
                return;
            }

            foreach (var folder in folderArray)
            {
                var srcPath = $"{NeatlyEditorConfig.PATH_ANDROID_TEMP_PROJECT}/unityLibrary/src/main/{folder}";
                var targetPath = srcPath.Replace(NeatlyEditorConfig.PATH_ANDROID_TEMP_PROJECT, NeatlyEditorConfig.PATH_ANDROID_PROJECT);
                PdrFileUtil.DeleteDirectory(targetPath);
                PdrFileUtil.CopyDirectory(srcPath, targetPath);
            }
        }

        #endregion

        #region iOS

        public static void IOSExport()
        {
            SetPlayerSetting();
            PlayerSettings.iOS.appleEnableAutomaticSigning = false;
            PlayerSettings.iOS.buildNumber = CommandParam.PatchCode.ToString();
            BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
            buildPlayerOptions.scenes = SCENE_LEVELS;
            buildPlayerOptions.locationPathName = NeatlyEditorConfig.PATH_IOS_PROJECT;
            buildPlayerOptions.target = BuildTarget.iOS;
            BuildPipeline.BuildPlayer(buildPlayerOptions);
        }

        //打包ios
        public static void IOSExportIpa()
        {
            var setting = BuildSetting.LocalServerSetting;
            var SchemeName = "Unity-iPhone";
            var Configuration = "Release";
            var SignIdentity = setting.mac_adhoc_identity;//"Apple Distribution: Kaffu Games Hong Kong Limited (Y978DF2H54)";
            var ProfileUUID = setting.mac_adhoc_uuid;//"aee0949c-eddf-4836-af24-b4d1114b0630";
            var archivePath = "./build/tmp/archive";

            // 清理工程
            PdrCMDHelper.ProcessCommand("xcodebuild",
                $"clean -project {SchemeName}.xcodeproj -scheme {SchemeName} -configuration {Configuration}", NeatlyEditorConfig.PATH_IOS_PROJECT);

            // 构建工程生成archive
            PdrCMDHelper.ProcessCommand("xcodebuild",
                $"archive -project {SchemeName}.xcodeproj -scheme {SchemeName} -configuration {Configuration} -destination generic/platform=ios -archivePath \"{archivePath}\" \"CODE_SIGN_IDENTITY\"=\"{SignIdentity}\" \"PROVISIONING_PROFILE_APP\"=\"{ProfileUUID}\"", NeatlyEditorConfig.PATH_IOS_PROJECT);

            // 导出adhoc ipa
            var exportDirectory = "./build/tmp/adhoc";
            var exportPlistPath = "./../overlay/ad-hoc.plist";
            PdrCMDHelper.ProcessCommand("xcodebuild",
                $"-exportArchive -archivePath \"{archivePath}.xcarchive\" -exportPath \"{exportDirectory}\" -exportOptionsPlist \"{exportPlistPath}\"", NeatlyEditorConfig.PATH_IOS_PROJECT);

            //导出dis ipa
            if (CommandParam.ExportDis)
            {
                exportDirectory = "./build/tmp/dis";
                exportPlistPath = "./../overlay/dis.plist";
                PdrCMDHelper.ProcessCommand("xcodebuild",
                    $"-exportArchive -archivePath \"{archivePath}.xcarchive\" -exportPath \"{exportDirectory}\" -exportOptionsPlist \"{exportPlistPath}\"", NeatlyEditorConfig.PATH_IOS_PROJECT);
            }

            NeatlyLocalServerHelper.PackageIOSIpaToLocalServer();
        }

        #endregion

        #region WebGL

        public static void WebGLExportProject()
        {
            SetPlayerSetting();
            PlayerSettings.iOS.appleEnableAutomaticSigning = false;
            BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
            buildPlayerOptions.scenes = SCENE_LEVELS;
            buildPlayerOptions.locationPathName = NeatlyEditorConfig.PATH_WEBGL;
            buildPlayerOptions.target = BuildTarget.WebGL;
            BuildPipeline.BuildPlayer(buildPlayerOptions);
        }

        #endregion

        #region Setting

        //设置PlayerSetting
        public static void SetPlayerSetting()
        {
            var setting = BuildSetting.ProjectBuildSetting;
            BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
            BuildTargetGroup group = BuildPipeline.GetBuildTargetGroup(target);
            PlayerSettings.companyName = CommandParam.CompanyName;
            PlayerSettings.productName = CommandParam.ProductName;
            PlayerSettings.applicationIdentifier = CommandParam.BundleIdentifier;
            PlayerSettings.bundleVersion = $"{CommandParam.Version}.{CommandParam.PatchCode}";
            PlayerSettings.SetScriptingBackend(group, ScriptingImplementation.IL2CPP);
            PlayerSettings.SetScriptingDefineSymbolsForGroup(group, CommandParam.Symbols);
            PlayerSettings.SetApiCompatibilityLevel(group, ApiCompatibilityLevel.NET_Standard);
            PlayerSettings.SetIl2CppCompilerConfiguration(group, Il2CppCompilerConfiguration.Release);
            EditorUserBuildSettings.development = CommandParam.Develop;
            EditorUserBuildSettings.allowDebugging = CommandParam.Develop;
            PlayerSettings.virtualRealitySplashScreen = null;
            //设置闪屏背景颜色
            var tx = AssetDatabase.LoadAssetAtPath<Texture2D>($"Assets/App/{CommandParam.Icon}.jpg");
            PlayerSettings.SplashScreen.show = false;
#if UNITY_ANDROID
            SetAndroidSetting();
            Texture2D[] icons = { tx, tx, tx, tx, tx, tx };
            PlayerSettings.SetIconsForTargetGroup(group, icons);
#elif UNITY_IOS
            SetIOSSetting();
			Texture2D[] icons = { tx, tx, tx, tx, tx, tx, tx, tx, tx, tx, tx, tx, tx, tx, tx, tx, tx, tx, tx };
            PlayerSettings.SetIconsForTargetGroup(group, icons);
#elif UNITY_STANDALONE_WIN
            SetWindowsSetting();
            Debug.Log(tx);
            Texture2D[] icons = {tx, tx, tx, tx, tx, tx, tx, tx};
            PlayerSettings.SetIconsForTargetGroup(group, icons);
#endif
            //不压缩代码
            PlayerSettings.stripEngineCode = false;
            //横竖屏
            PlayerSettings.defaultInterfaceOrientation = UIOrientation.AutoRotation;
            PlayerSettings.allowedAutorotateToPortrait = setting.is_portrait;
            PlayerSettings.allowedAutorotateToPortraitUpsideDown = setting.is_portrait_upside_down;
            PlayerSettings.allowedAutorotateToLandscapeLeft = setting.is_landscape_left;
            PlayerSettings.allowedAutorotateToLandscapeRight = setting.is_landscape_right;
            //是否调试
            EditorUserBuildSettings.connectProfiler = false;
        }

        public static void SetWeChatPlayerSetting()
        {
            SetPlayerSetting();
            BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
            BuildTargetGroup group = BuildPipeline.GetBuildTargetGroup(target);
            PlayerSettings.SetScriptingDefineSymbolsForGroup(group, $"{CommandParam.Symbols}WEIXINMINIGAME;");
        }

        //设置Android
        private static void SetAndroidSetting()
        {
            var setting = BuildSetting.ProjectBuildSetting;
            PlayerSettings.Android.splashScreenScale = AndroidSplashScreenScale.ScaleToFill;
            PlayerSettings.Android.minSdkVersion = AndroidSdkVersions.AndroidApiLevel22;
            PlayerSettings.Android.androidIsGame = true;
            PlayerSettings.Android.androidTVCompatibility = true;
            PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARM64 | AndroidArchitecture.ARMv7;
            PlayerSettings.Android.keystoreName = PdrCombine.ProjectRoot($"/android/key/{setting.android_key_store_name}.keystore");
            PlayerSettings.Android.keystorePass = setting.android_key_store_pass;
            PlayerSettings.Android.keyaliasName = setting.android_key_alias_name;
            PlayerSettings.Android.keyaliasPass = setting.android_key_alias_pass;
            PlayerSettings.Android.bundleVersionCode = CommandParam.PatchCode;
            EditorUserBuildSettings.androidBuildSubtarget = MobileTextureSubtarget.ASTC;
            EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
            EditorUserBuildSettings.androidBuildType = AndroidBuildType.Release;
        }

        //设置IOS
        private static void SetIOSSetting()
        {
            PlayerSettings.iOS.targetDevice = iOSTargetDevice.iPhoneAndiPad;
            PlayerSettings.iOS.sdkVersion = iOSSdkVersion.DeviceSDK;
            PlayerSettings.iOS.hideHomeButton = true;
            PlayerSettings.iOS.requiresFullScreen = true;
            PlayerSettings.iOS.deferSystemGesturesMode = SystemGestureDeferMode.All;
            PlayerSettings.iOS.SetLaunchScreenImage(GetSplashTexture(), iOSLaunchScreenImageType.iPadImage);
            PlayerSettings.iOS.SetLaunchScreenImage(GetSplashTexture(), iOSLaunchScreenImageType.iPhoneLandscapeImage);
            PlayerSettings.iOS.SetLaunchScreenImage(GetSplashTexture(), iOSLaunchScreenImageType.iPhonePortraitImage);
            PlayerSettings.iOS.SetiPhoneLaunchScreenType(iOSLaunchScreenType.ImageAndBackgroundConstant);
            PlayerSettings.SetArchitecture(BuildTargetGroup.iOS, 1);
        }

        private static void SetWindowsSetting()
        {
            PlayerSettings.allowFullscreenSwitch = false;
            PlayerSettings.runInBackground = true;
            PlayerSettings.defaultScreenWidth = 640;
            PlayerSettings.defaultScreenHeight = 1136;
            PlayerSettings.fullScreenMode = FullScreenMode.Windowed;
            PlayerSettings.resizableWindow = true;
        }

        #endregion

        private static Texture2D GetSplashTexture()
        {
            return AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/App/splash.jpg");
        }

        private static Sprite GetSplashSprite()
        {
            var sprite = AssetDatabase.LoadAssetAtPath<Sprite>("Assets/App/splash.jpg");
            return sprite;
        }
    }
}

//EditorUtility.DisplayDialog("ICON图标未找到", "路径" + string.Format("Assets/App/{0}.png", ""), "OK");